package br.com.massai.controller.filters;

import java.io.IOException;

import javax.ejb.EJB;
import javax.faces.FactoryFinder;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.massai.model.beans.SessionBean;
import br.com.massai.model.entity.Collaborator;
import br.com.massai.model.entity.Url;
import br.com.massai.model.exceptions.SystemException;
import br.com.massai.view.enums.Role;
import br.com.massai.view.utils.FacesUtil;
import br.com.massai.view.utils.MassaiUtil;

@SuppressWarnings("all")
@WebFilter("/LoggedInFilter")
public class LoggedInFilter implements Filter {

	public static String context;
	private FilterConfig config;
	private ServletContext servletContext;

	@EJB private SessionBean sessionBean;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
		this.servletContext = this.config.getServletContext();
		this.context = this.servletContext.getContextPath();
	}

	//http://www.guj.com.br/java/91709-facescontextgetcurrentinstance-is-null-como-iniciar-o-contexto-no-codigo-java

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String url = httpRequest.getRequestURL().toString();
		String context = this.config.getServletContext().getContextPath();
//		boolean isLoginPage = url.contains("/login.xhtml");

		Collaborator userHandler = (Collaborator) FacesUtil.obterAtributoSessao(getFacesContext(request, response), MassaiUtil.USER_LOGGED);

		if(((HttpServletRequest) request).getSession() != null){
			if(userHandler != null && userHandler.getId() != null) //MassaiUtil.isLogIn()
				chain.doFilter(request, response);
			else 
				((HttpServletResponse) response).sendRedirect(context + "/login.xhtml");

		} else
			((HttpServletResponse) response).sendRedirect(context + "/pages/home.xhtml");

//		if(userHandler != null && userHandler.getId() != null && !isLoginPage){
//			if(sessionBean.getUrlByUser() != null && !sessionBean.getUrlByUser().isEmpty()){
//				for(Url u : sessionBean.getUrlByUser())
//					if(MassaiUtil.isAdmin() || url.contains(u.getUrl()) 
//						|| url.contains("/pages/home.xhtml") 
//						|| url.contains("/pages/user/passwordChange.xhtml")){
//						chain.doFilter(request, response);
//						return;
//					}
//			}
//		}
//		redirect((HttpServletResponse) response, context + "/login.xhtml");
	}

	private void redirect(HttpServletResponse httpResponse, String url) throws IOException{
		httpResponse.sendRedirect(url);
	}
	
	private void checkPermissionAccess(String url) throws IOException, SystemException {
		
	}

	@Override
	public void destroy() { }
	
	private FacesContext getFacesContext(ServletRequest request, ServletResponse response) {  
        FacesContext facesContext = FacesContext.getCurrentInstance();

        if (facesContext != null)
            return facesContext;

        FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
        LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
        Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);

        facesContext = contextFactory.getFacesContext(this.servletContext, request, response, lifecycle);

        InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);

        UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, "/portal/"); //Tecea
        facesContext.setViewRoot(view);

        return facesContext;
    }

	private abstract static class InnerFacesContext extends FacesContext {
        protected static void setFacesContextAsCurrentInstance(FacesContext facesContext) {
            FacesContext.setCurrentInstance(facesContext);
        }
    }
}